﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.Web;

namespace PAS.Helper
{
    public class DataConnHelper
    {
        
        public static string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+AppDomain.CurrentDomain.BaseDirectory+"Apply.mdb";    
        public DataTable GetDataTable(string sql)
        {
            DataTable result = new DataTable();
            OleDbDataAdapter da = new OleDbDataAdapter(sql, ConnectionString);
            try
            {
                da.Fill(result);
            }
            finally
            {
                da.Dispose();
                da = null;
            }
            return result;
        }

        public static bool IsLogin
        {
            get
            {
                object obj = HttpContext.Current.Session["IsLogin"];
                return (obj != null && Convert.ToBoolean(obj));
            }
            set
            {
                HttpContext.Current.Session["IsLogin"] = value;
            }
        }

        public int ExecSqlCommand(string commSql)
        {
            int reuslt = 0;
            OleDbConnection conn = new OleDbConnection(ConnectionString);
            OleDbCommand comm = new OleDbCommand();
            try
            {
                conn.Open();
                comm.CommandText = commSql;
                comm.CommandType = CommandType.Text;
                comm.Connection = conn;
                comm.CommandTimeout = 900;
                reuslt = comm.ExecuteNonQuery();
            }
            finally
            {
                comm.Dispose();
                conn.Close();
            }
            return reuslt;
        }

        public Hashtable GetHashtableByNames(string dbTableName,string dbKeyColumnName, string orderByString)
        {
            Hashtable result = new Hashtable();
            string sql = "Select * From " + dbTableName + orderByString;
            DataTable dt = GetDataTable(sql);
            for(var i=0; dt!=null && dt.Rows.Count > 0 && i<dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string strKeyVal = Convert.ToString(dr[dbKeyColumnName]);
                if (!result.Contains(strKeyVal))
                    result.Add(strKeyVal, dr);
            }
            return result;
        }

        public bool CheckLogin(string pwd)
        {
            DataTable dt = GetDataTable("Select UserCode From UserInfo Where UserCode='sysAdmin' and Pwd='"+pwd+"'");
            return (dt != null && dt.Rows.Count > 0);
        }
    }
}